package com.example.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.utils.jwt.JwtUtils;
import com.example.sys.entity.User;
import com.example.sys.entity.UserInfo;
import com.example.sys.mapper.UserMapper;
import com.example.sys.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZhengDing
 * @since 2022-02-19 22:26:17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Override
    public String login(String username, String password) {
        if (verifyUser(username, password)) {
            User user = getUserByUsername(username);
            UserInfo userInfo = new UserInfo(user);
            String jwtToken = JwtUtils.createJWTToken(userInfo);
            return jwtToken;
        }
        return null;
    }
    
    public User getUserByUsername(String username) {
        User queryParams = new User();
        queryParams.setUsername(username);
        User user = this.getOne(new LambdaQueryWrapper<User>(queryParams));
        return user;
    }
    
    public boolean verifyUser(String username, String password) {
        User user = getUserByUsername(username);
        if (user == null) {
            return false;
        }
        
        if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
            return true;
        }
        return false;
    }
    
    public boolean isUserNameExist(String username) {
        long count = this.count(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (count == 1) {
            return true;
        }
        return false;
    }
}
